#include <string>
 #include <sys/socket.h>
 #include <netinet/in.h>
 #include <cstring>
 #include <arpa/inet.h>
 #include <iostream>
 #include <unistd.h>
 #include <sys/wait.h>

using namespace std;


class TcpServer
{
    void Service(int fd, struct sockaddr_in& peer)
    {
        char buffer[80];
        while(1)
        {
            int n= read(fd, buffer, sizeof(buffer)-1);
            if(n> 0)
            {
                buffer[n]= 0;
                cout<<"client say# "<<buffer<<endl;

                string ret= "server echo# ";
                ret+= buffer;
                write(fd, ret.c_str(), ret.size());
            }
            else if(n== 0)
            {
                cout<<"连接断开，客户端为："<<inet_ntoa(peer.sin_addr)<<" "<<ntohs(peer.sin_port)<<endl;
                break;
            }
        }
    }

    void ProcessHandle(int fd, struct sockaddr_in& peer)
    {
        if(fork()==0)
        {
            close(_sockfd);//关闭监听套接字
            if(fork()>0)
            {
                exit(0);
            }
            else
            {
                Service(fd, peer);
                close(fd);
                exit(0);
            }
        }
        else
        {
            wait(nullptr);
            close(fd);//关闭通信套接字
        }

    }
public:
    TcpServer(int port)
    :_port(port)
    {}

    void Init()
    {
        _sockfd= socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family= AF_INET;
        local.sin_addr.s_addr= htonl(INADDR_ANY);
        local.sin_port= htons(_port);

        int opt=1;
        setsockopt(_sockfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
        bind(_sockfd, (struct sockaddr*)&local, sizeof(local));

        listen(_sockfd, 8);
    }

   

    void Start()
    {
        _isrunning= true;

        while(_isrunning)
        {
            struct sockaddr_in peer;
            socklen_t len= sizeof(peer);
            int fd= accept(_sockfd, (struct sockaddr*)&peer, &len);

            cout<<"client connected: "<<inet_ntoa(peer.sin_addr)<<" "<<ntohs(peer.sin_port)<<endl;
            ProcessHandle(fd, peer);


        }

    }

private:
    int _port;
    int _sockfd;
    bool _isrunning;
};


int main()
{
    TcpServer server(8888);
    server.Init();
    server.Start();

    return 0;
}